<template>
  <div>
    <h2>航班信息列表</h2>
    <p>
      <RouterLink to='/booking' class="home-link">返回</RouterLink>
    </p>
    <button @click="exportData" class="ebutton">导出</button>
    <div class="flight-table">
      <div class="flight-header">
        <p>航班号</p>
        <p>日期</p>
        <p>出发地 -> 目的地</p>
        <p>操作</p>
      </div>
      <div v-for="(flight, index) in flights" :key="flight.id" class="flight-row">
        <p class="flight-number">{{ flight.id }}</p>
        <p class="flight-date">{{ parseTime(flight.date) }}</p>
        <p class="flight-destinations">{{ flight.bdestination }} -> {{ flight.edestination }}</p>
        <div class="flight-actions">
          <div>
            <select v-model="flight.cabinSelection">
              <option v-for="(item, itemIndex) in flight.typeCount" :value="item.id" :key="itemIndex"> {{
                  item.type
                }}(剩余:
                {{ item.count }})
              </option>
            </select>
            <button v-if="flight.typeCount.some(item => item.type !== '')"
                    @click="decreaseTicketQuantity(flight, index)" class="decrease-button">-
            </button>
            <span>{{ tickets[index] }}</span>
            <button v-if="flight.typeCount.some(item => item.type !== '')"
                    @click="increaseTicketQuantity(flight, index)" class="increase-button">+
            </button>
          </div>

          <!--          <button @click="confirmBooking(flight.id, index)" class="action-button">订票</button>-->
          <button @click="handleAdd(flight.id, index)" class="action-button" :disabled="tickets[index] === 0">订票
          </button>
<!--          <button @click="bookTicket(flight)" :disabled="tickets[index] === 0">候补</button>-->
          <!--          <button @click="bookTicket(flight)">候补</button>-->

          <button
          @click="handleWait(flight, index)"
              :disabled="flight.typeCount.some(item => item.count > 0) && !flight.cabinSelection">候补
          </button>

        </div>
      </div>
    </div>
    <!-- 添加购买人信息对话框 -->
    <el-dialog title="添加购买人信息" v-model="orderOpen" width="54%">
      <el-form ref="form" v-for="(item,index) in ordersList" :model="item" :key="index" :rules="rules"
               label-width="110px">
        <el-divider content-position="left">购买人{{ index + 1 }}</el-divider>
        <el-form-item label="座位号" prop="seatId">
          <el-input v-model="item.seatId" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="身份ID" prop="userUserId">
          <el-input v-model="item.userUserId" placeholder="请输入使用机票用户ID"/>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="submitOrder">添加购买人信息</el-button>
      </span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmBooking">确 定</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </div>
    </el-dialog>

<!--   候补人信息 -->
    <el-dialog title="添加购买人信息" v-model="waitOpen" width="54%">
      <el-form ref="form" v-for="(item,index) in ordersListWait" :model="item" :key="index" :rules="rules"
               label-width="110px">
        <el-divider content-position="left">购买人{{ index + 1 }}</el-divider>
        <el-form-item label="座位号" prop="seatId">
          <el-input v-model="item.seatId" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="身份ID" prop="userUserId">
          <el-input v-model="item.userUserId" placeholder="请输入使用机票用户ID"/>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="submitOrder">添加购买人信息</el-button>
      </span>
      <div slot="footer" class="dialog-footer">
<!--        <el-button type="primary" @click="bookTicket(flight)">确 定</el-button>-->
        <el-button type="primary" @click="bookTicket(currentFlightId, currentFlightIndex)">确 定</el-button>
<!--        <el-button type="primary" @click="bookTicket">确 定</el-button>-->
        <el-button @click="cancelWait">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {BookOrder, ExcelDownload, SelectFlights, WaitOrder} from '@/api/index.js';
import {parseTime} from "../utils/time.js";
import index from "vuex";

export default {
  computed: {
    index() {
      return index
    }
  },
  data() {
    return {
      flights: [],
      clazz: '',
      tickets: [],
      FlightDTO: null,
      // 订票信息
      ordersList: [],
      //候补信息
      ordersListWait:[],
      useUserId: '',
      form: {},
      rules: {
        seatId: [
          {required: true, message: "座位号不能为空", trigger: "blur"}
        ],
        userUserId: [
          {required: true, message: "姓名不能为空", trigger: "blur"}
        ]
      },
      orderOpen: false, // 订票对话框显示状态
      waitOpen: false,  // 候补对话框显示状态
      currentFlightId: null, // 当前选中的航班ID
      currentFlightIndex: null // 当前选中的航班索引
    };
  },

  created() {
    this.FlightDTO = this.$route.query;
    console.log('flight:', this.FlightDTO)
  },
  mounted() {
    SelectFlights(this.FlightDTO).then(value => {
      this.flights = value.data.data.map(flight => ({
        ...flight,
        cabinSelection: '', // 初始化舱位选择
      }));
      console.log(this.flights);
      // 初始化tickets数组
      this.tickets = this.flights.map(() => 0);
    });

  },

  methods: {
    parseTime,
    exportData() {
      // 导出数据为Excel文件
      ExcelDownload(this.FlightDTO, 'flightData.xlsx')
          .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '航班信息数据.xlsx'); // 设置下载的文件名
            document.body.appendChild(link);
            link.click();
            alert('数据已导出')
          }).catch(error => {
        console.error('导出失败:', error.response ? error.response.data : error.message);
      });
    },
    // 增加票数,加号操作
    increaseTicketQuantity(flight, index) {
      // 获取当前选中的舱位类型
      let selectedCabin = flight.typeCount[flight.cabinSelection - 1];
      // 检查是否还有剩余票数
      if (this.tickets[index] < selectedCabin.count) {
        this.tickets[index] += 1;
      }
    },
    // 减少票数，减号操作
    decreaseTicketQuantity(flight, index) {
      // 获取当前选中的舱位类型
      let selectedCabin = flight.typeCount[flight.cabinSelection - 1];
      // 检查票数是否大于0，并且减少后不会超过剩余票数
      if (this.tickets[index] > 0 && this.tickets[index] <= selectedCabin.count) {
        this.tickets[index] -= 1;
      }
    },
    /** 新增按钮操作 */
    handleAdd(flightId, index) {
      this.reset();
      this.orderOpen = true;
      this.currentFlightId = flightId; // 存储当前选中的航班ID
      this.currentFlightIndex = index; // 存储当前选中的航班索
      // 推入一个订单填写表单
      this.ordersList.push({
        seatId: '',
        userUserId: '',
      })
    },
    //候补操作按钮
    handleWait(flight, index) {
      if (flight.typeCount[flight.cabinSelection - 1] && flight.typeCount[flight.cabinSelection - 1].count > 0) {//判断是否有余票
        alert('尚有余票,请选择订票');
      } else {
        this.reset();
        this.waitOpen = true;
        this.currentFlightId = flight.id; // 存储当前选中的航班ID
        this.currentFlightIndex = index; // 存储当前选中的航班索引
        // 推入一个订单填写表单
        this.ordersListWait.push({
          seatId: '',
          userUserId: '',
        })
      }
    },
    // 取消订单按钮
    cancelAdd() {
      this.orderOpen = false;
      this.reset();
    },
    // 取消候补按钮
    cancelWait() {
      this.waitOpen = false;
      this.reset();
    },
    submitOrder() {
      this.reset();
      this.open = true;
      this.ordersList.push({
        seatId: '',
        userUserId: '',
      })
    },
    // 表单重置
    reset() {
      this.form = {
        /*id: null,*/
        seatId: null,
        userUserId: null,
        ordersList: [],
      };
    },
    // 确认订票
    confirmBooking() {
      const flightId = this.currentFlightId;
      const index = this.currentFlightIndex;
      const flight = this.flights.find(f => f.id === flightId);
      // orderUserid
      const orderUserId = sessionStorage.getItem("userId");
      const data = this.ordersList.map(item => {
        return {
          orderUserId,
          flightId: flightId,
          clazz: flight.cabinSelection,
          tickets: this.tickets[index],
          seatId: item.seatId,
          useUserId: item.userUserId
        };
      })
      if (data.length > 0) {
        // 发送请求
        if (this.tickets[index]) {
          BookOrder(data).then((res) => {
            if (res.data.success === false) {
              this.$message.error('预定失败' + res.data.errorMsg);
            } else {
              this.$message.success('预定成功');
            }
            this.orderOpen = false; // 关闭对话框
          }).catch((error)=>{
            this.$message.error('预定失败'+error);
          })

        } else {
          this.$message.warning('请预定票的数目');
        }
      } else {
        this.$message.warning('请输入购买人信息')
      }
    },
    //候补
   /* bookTicket(flight) {
      const flightId = flight.id;
      const orderUserId = sessionStorage.getItem("userId");
      const index = this.flights.findIndex(f => f.id === flightId);
      if (orderUserId) {
        const data = {
          orderUserId,
          flightId: flightId,
          clazz: flight.cabinSelection,
          tickets: 1 // 默认候补1张票
        };
        // 向后端发送候补请求
        WaitOrder(data).then(() => {
          // if (this.tickets[index])//判断是否有票，可以不加，已经硬编码了候补一张票，this.tickets[index]值永远为1
          alert('候补成功');
        }).catch(error => {
          console.error('候补失败:', error);
          alert('候补失败，请稍后再试');
        });
      } else {
        alert('请先登录');
      }
    }*/
    bookTicket(flightId, index) {
      const orderUserId = sessionStorage.getItem("userId");
      if (orderUserId) {
        /*const data = {
          seatId: item.seatId,
          useUserId: item.userUserId,
          orderUserId,
          flightId: flightId,
          clazz: this.flights[index].cabinSelection,
          tickets: 1 // 默认候补1张票
        };*/
        const data = this.ordersListWait.map(item => {
          return {
            seatId: item.seatId,
            useUserId: item.userUserId,
            orderUserId,
            flightId: flightId,
            clazz: this.flights[index].cabinSelection,
            tickets: 1 // 默认候补1张票
          };
        })
        // 向后端发送候补请求
        WaitOrder(data).then(() => {
          alert('候补成功');
          this.waitOpen = false; // 关闭对话框
        }).catch(error => {
          console.error('候补失败:', error);
          alert(error);
        });
      } else {
        alert('请先登录');
      }
    }

  },
}
</script>

<style scoped>
.ebutton {
  height: 30px;
  width: 60px;
}

.home-link {
  font-size: 16px;
  color: #dddddd;
  text-decoration: none;
  /* 去除下划线 */
  padding: 5px 15px;
  /* 增加一些内边距 */
  border-radius: 7px;
  /* 增加圆角 */
  background-color: #383737;
  /* 设置背景颜色 */
  cursor: pointer;
  /* 鼠标悬停时显示小手样式 */
}

.home-link:hover {
  background-color: #4c4b4b;
  /* 鼠标悬停时的背景颜色 */
}

.flight-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  font-family: 'Arial', sans-serif;
  /* 设置字体 */
}

.flight-header {
  background-color: #adadae;
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 两端对齐 */
  padding: 10px; /* 统一内边距 */
}

.flight-row {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 两端对齐 */
  padding: 10px; /* 统一内边距 */
}

.flight-row:hover {
  background-color: #f8f9fa;
  /* 鼠标悬浮时的背景颜色 */
}

.flight-header p, .flight-row p {
  flex: 1; /* 让每个单元格占据相同的空间 */
  margin: 0 10px; /* 统一外边距 */
  text-align: center; /* 水平居中对齐文本 */
}

.flight-date,
.flight-number,
.flight-destinations {
  flex: 1;
  margin: 0 10px;
}

/* 为操作列添加特殊样式，如果它不需要占据相同的空间 */
.flight-actions {
  flex: 0; /* 不让操作列占据额外空间 */
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.action-button {
  padding: 8px 15px;
  margin-left: 10px;
  border: none;
  border-radius: 5px;
  /* 圆角边框 */
  background-color: #4c93af;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.1s;
  /* 过渡效果 */
}

.action-button:disabled {
  background-color: #6c757d;
  /* 禁用按钮的背景颜色 */
  cursor: not-allowed;
}

.action-button:not(:disabled):hover {
  background-color: #08668c;
  /* 鼠标悬浮时的背景颜色 */
  transform: scale(1.05);
  /* 放大效果 */
}

button {
  padding: 5px 10px;
  cursor: pointer;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.increase-button, .decrease-button {
  height: 20px;
  width: 25px;
  padding: 2px 6px; /* 更小的内边距 */
  font-size: 12px; /* 更小的字体大小 */
  border-radius: 3px; /* 可选：更小的圆角边框 */
  border: 1px solid #ccc;
  margin-left: 5px; /* 在按钮之间添加一些间距 */
  margin-right: 5px; /* 在按钮和数字之间添加一些间距 */
}

.dialog-footer {
  width: 500px;
  height: 60px;
  margin-left: 300px;
}
</style>